import { useDispatch, useSelector } from 'react-redux'
import { Dispatch } from 'redux'
import { RootState } from '@/types/store'
import { useHistory } from 'react-router-dom'
import {
  getArticleListByChannelId,
  getNewestArticleList,
} from '@/store/actions/home'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
import ArticleItem from '@/components/ArticleItem'

import styles from './index.module.scss'

type Props = {
  channelId: number
}
const ArticleList = ({ channelId }: Props) => {
  console.log(channelId)

  const history = useHistory()

  const dispatch = useDispatch<Dispatch<any>>()

  const { channelArticles } = useSelector((state: RootState) => state.home)

  const currentChannelArticles = channelArticles[channelId] ?? {
    pre_timestamp: Date.now() + '',
    results: [],
  }
  const { pre_timestamp, results } = currentChannelArticles
  console.log(pre_timestamp, results)

  const loadMore = async () => {
    await dispatch(getArticleListByChannelId(channelId, pre_timestamp))
  }

  const onRefresh = async () => {
    await dispatch(getNewestArticleList(channelId, Date.now() + ''))
  }

  const hasMore = pre_timestamp !== null

  return (
    <div className={styles.root}>
      <PullToRefresh onRefresh={onRefresh}>
        {/* 文章列表中的每一项 */}
        {results.map((item, index) => {
          const {
            art_id,
            title,
            aut_name,
            comm_count,
            pubdate,
            cover: { type, images },
          } = item

          const articleData = {
            title,
            aut_name,
            comm_count,
            pubdate,
            type,
            images,
          }

          return (
            <div
              key={index}
              className="article-item"
              onClick={() => history.push(`/articles/${art_id}`)}
            >
              <ArticleItem {...articleData} />
            </div>
          )
        })}

        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={0} />
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
